package com.tamakloe.guestbook;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tanesha.recaptcha.*;

@SuppressWarnings("serial")
public class SignGuestbookServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(SignGuestbookServlet.class.getName());
    private static final String VIEW = "guestbookform.jsp";
    private static final String ATTRIBUTE_FORM = "form";
    private static final String ATTRIBUTE_USER = "greeting";
    private static final String ATTRIBUTE_RECAPTCHA = "capthcahtml";
    private static final String publicKey = "6LcBgwYAAAAAAAUb3EPSSVOTuYKOODicHd8iFLeT";

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        // Prepare form bean.
    	Greeting g = new Greeting();
        GuestForm guestForm = new GuestForm(g);
        req.setAttribute(ATTRIBUTE_FORM, guestForm);

        // Process request and get result.
        g = guestForm.registerGreeting(req);
        if (!guestForm.isSuccess()){
	        req.setAttribute(ATTRIBUTE_USER, g);
		   	ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
			reCaptcha.setPublicKey(publicKey);
			reCaptcha.setIncludeNoscript(true);
			String chtml = reCaptcha.createRecaptchaHtml("", null);
	     	// set reCaptcha html
		    req.setAttribute(ATTRIBUTE_RECAPTCHA, chtml);	        
	        // Postback.
	        try {
				req.getRequestDispatcher(VIEW).forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log.warning(ATTRIBUTE_FORM + e.getMessage()); 
			}        
        } else {
        	resp.sendRedirect("/guestbooklist");
        }



    }
    
 @Override
 	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    		throws ServletException, IOException {
	 ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
	 reCaptcha.setPublicKey(publicKey);
	 reCaptcha.setIncludeNoscript(true);
	 
	 String chtml = reCaptcha.createRecaptchaHtml("", null);
     	// Set Attribute
	    req.setAttribute(ATTRIBUTE_RECAPTCHA, chtml);
	    // Show view.
	    req.getRequestDispatcher(VIEW).forward(req, resp);

    }   
}
